package com.university.dialog;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.university.utils.Flag;
import com.university.utils.SqliteDatabaseManager;


//猜想：两个ASYNCTASK都是在UI线程中创建的，应该是排队执行，一个执行完了 另一个才开始执行。
public class GetMajorDataDialog {
	private Context mContext;
	private ProgressDialog dialog;
	private SqliteDatabaseManager manager;
	public GetMajorDataDialog(Context context) {
		mContext=context;
		dialog=new ProgressDialog(mContext, ProgressDialog.STYLE_SPINNER);
		dialog.setTitle("提示");
		dialog.setMessage("正在更新数据，请稍等...");
		dialog.setCancelable(false);
		dialog.show();
		manager=SqliteDatabaseManager.getInstance(mContext);
		new AsyncTask<Void, Void, String>(){
			@Override
			protected String doInBackground(Void... params) {
				HttpClient client=new DefaultHttpClient();
				client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
				client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
				HttpGet get=new HttpGet(Flag.MajorUrl);
				try {
					HttpResponse response=client.execute(get);
					if(response.getStatusLine().getStatusCode()!=200) {
						return null;
					}else {
						//初步判断，估计是这个方法内部实现很可能创建了大量的string 片段  直接造成了常量池的溢出
						//这一段代码留在这儿，这儿之前之所以会造成内存溢出的原因就是，EntityUtils.toString 是一个静态方法
						//而静态方法一旦引用了这段数据， 则数据就会得不到释放，造成所谓的额内存泄露。从而造成内存溢出
//						String values=EntityUtils.toString(response.getEntity(), "UTF-8");
						
						StringBuilder builder=new StringBuilder();
						InputStream is=response.getEntity().getContent();
						
						byte[] buffer=new byte[2048];
						int len=0;
						while (-1!=(len=is.read(buffer))) {
							builder.append(new String(buffer, 0, len, "UTF-8"));
						}
						//读取完毕，关闭数据流
						if (is!=null) {
							is.close();
						}
						String values=builder.toString();
						String[] strs=values.split("\n");
						values=null;
						JSONArray array=null;
						JSONArray a=null;
						ArrayList<ContentValues> arrayList=new ArrayList<ContentValues>();
						ContentValues value=null;
						for (String str : strs) {
							array=new JSONArray(str);
							//将一段数据转化，插入
							for (int i = 0; i < array.length(); i++) {
								a=array.getJSONArray(i);
								value=new ContentValues();
								try {
									value.put("院校代码", a.getString(0));
									value.put("专业名称", a.getString(1));
									value.put("录取数", a.getInt(2));
									value.put("最高分", a.getInt(3));
									value.put("最低分", a.getInt(4));
									value.put("平行志愿", a.getInt(5));
									value.put("征求志愿", a.getInt(6));
									value.put("服从志愿", a.getInt(7));
									value.put("文理", a.getString(8));
								} catch (JSONException e) {
									e.printStackTrace();
								}
								arrayList.add(value);
							}
							//一次数据库事物写入
							manager.insertMajorData(arrayList);
							//插入完成后，将列表清空，防止内存泄露
							arrayList.clear();
						}
						//释放string数组的内存
						strs=null;
						return "OK";
					}
					
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (JSONException e1) {
					e1.printStackTrace();
				}
				return null;
			}

			@Override
			protected void onPostExecute(String result) {
				if (result==null) {
					dialog.dismiss();
					Toast.makeText(mContext, "网络连接异常", 0).show();
				}else  {
					dialog.dismiss();
					Toast.makeText(mContext, "网络连接成功", 0).show();
				}
			}
			
		}.execute();
		}
		public void disMiss(){
			dialog.dismiss();
		}
		public void show(){
			dialog.show();
		}
}
